package com.drm.netschool.web.interceptor;

import java.lang.reflect.Method;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.drm.common.util.ApplicationContextUtil;
import com.drm.common.util.ConfigUtil;
import com.drm.common.util.CookieUtil;
import com.drm.common.util.StringUtil;
import com.drm.common.util.constants.Constants;
import com.drm.netschool.entity.DrmUser;
import com.drm.netschool.service.DrmUserCacheService;
import com.drm.netschool.web.annotation.AccessRequired;

/**
 * Created by CUIJB on 2015年7月25日
 */
public class UserAccessApiInterceptor extends HandlerInterceptorAdapter {

	@SuppressWarnings("deprecation")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String url = request.getRequestURI();
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		AccessRequired annotation = method.getAnnotation(AccessRequired.class);
		if (annotation != null) {
			CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
			String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID	,	false);
			String uidPk = cookieUtil.getCookie(Constants.COOKIE_USER_ID_PK	,	false);
			boolean  isRightCookie =   CookieUtil.checkCookieIdIsOk(key,uidPk);
			
			if (StringUtil.empty(key) || !isRightCookie) {
				response.sendRedirect(Constants.DOMAIN + "/member/login?redirectURL=" + URLEncoder.encode(url));
				return false;
			}
			DrmUser user = null;
			try {
				DrmUserCacheService userCacheService = ApplicationContextUtil.getBean(DrmUserCacheService.class);
				if (!StringUtil.empty(key))
					user = userCacheService.getUserCache(key);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (user == null) {
				response.sendRedirect(Constants.DOMAIN + "/member/login?redirectURL=" + URLEncoder.encode(url));
				return false;
			}
		}
		return true;
	}
}
